<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Programming in Lua : 26.2</title>
<link rel="stylesheet" type="text/css" href="pil.css">
</head>
<body>
<p class="warning">
<A HREF="contents.html"><IMG TITLE="Programming in Lua (first edition)" SRC="capa.jpg" ALT="" ALIGN="left"></A>This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.<BR>The third edition targets Lua 5.2 and is available at <A HREF="http://www.amazon.com/exec/obidos/ASIN/859037985X/theprogrammil3-20">Amazon</A> and other bookstores.<BR>By buying the book, you also help to <A HREF="../donations.html">support the Lua project</A>.
</p>
<table width="100%" class="nav">
<tr>
<td width="10%" align="left"><a href="26.1.html"><img border="0" src="left.png" alt="Previous"></a></td>
<td width="80%" align="center"><a href="contents.html"><font face="Helvetica,Arial,sanserif">
<font color="gray">Programming in </font><font color="blue"> Lua</font>
</font></a></td>
<td width="10%" align="right"><a href="27.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
<tr>
<td width="10%" align="left"></td>
<td width="80%" align="center"><a href="contents.html#P4">Part IV. The C API</a>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="contents.html#26">Chapter 26. Calling C from Lua</a></td>
<td width="10%" align="right"></td></tr>
</table>
<hr/>
<p><h2>26.2 &ndash; C Libraries</h2>

<p>A Lua library is a chunk that defines several Lua functions
and stores them in appropriate places,
typically as entries in a table.
A C library for Lua mimics this behavior.
Besides the definition of its C functions,
it must also define a special function that corresponds
to the main chunk of a Lua library.
Once called, this function registers all C functions
of the library and stores them in appropriate places.
Like a Lua main chunk,
it also initializes anything else that needs initialization
in the library.

<p>Lua "sees" C functions through this registration process.
Once a C function is represented and stored in Lua,
a Lua program calls it through direct reference to its address
(which is what we give to Lua when we register a function).
In other words, Lua does not depend on a function name,
package location, or visibility rules to call a function,
once it is registered.
Typically, a C library has one single public (extern) function,
which is the function that opens the library.
All other functions may be private,
declared as <code>static</code> in C.

<p>When you extend Lua with C functions,
it is a good idea to design your code as a C library,
even when you want to register only one C function:
Sooner or later (usually sooner) you will need other functions.
As usual, the auxiliary library offers a helper function for this job.
The <code>luaL_openlib</code> function receives a list of C functions
and their respective names
and registers all of them inside a table with the library name.
As an example, suppose we want to create a library with
the <code>l_dir</code> function that we defined earlier.
First, we must define the library functions:
<pre>
    static int l_dir (lua_State *L) {
       ...  /* as before */
    }
</pre>
Next, we declare an array with all functions and their respective names.
This array has elements of type <code>luaL_reg</code>,
which is a structure with two fields:
a string and a function pointer.
<pre>
    static const struct luaL_reg mylib [] = {
      {"dir", l_dir},
      {NULL, NULL}  /* sentinel */
    };
</pre>
In our example, there is only one function (<code>l_dir</code>) to declare.
Notice that the last pair in the array must be <code>{NULL, NULL}</code>,
to signal its end.
Finally, we declare a main function,
using <code>luaL_openlib</code>:
<pre>
    int luaopen_mylib (lua_State *L) {
      luaL_openlib(L, "mylib", mylib, 0);
      return 1;
    }
</pre>
The second argument to <code>luaL_openlib</code> is the library name.
This function creates (or reuses) a table with the given name,
and fills it with the pairs name-function specified by the
array <code>mylib</code>.
The <code>luaL_openlib</code> function also
allows us to register common upvalues
for all functions in a library.
For now, we are not using upvalues,
so the last argument in the call is zero.
When it returns,
<code>luaL_openlib</code> leaves on the stack the table wherein it
opened the library.
The <code>luaopen_mylib</code> function returns 1 to return this value to Lua.
(As with Lua libraries, this return is optional,
because the library is already assigned to a global variable.
Again, like in Lua libraries,
it costs nothing, and may be useful occasionally.)

<p>After finishing the library,
we must link it to the interpreter.
The most convenient way to do it
is with the dynamic linking facility,
if your Lua interpreter supports this facility.
(Remember the discussion about
dynamic linking in <a href="8.2.html#C-packages">Section 8.2</a>.)
In this case, you must create a dynamic library with your code
(a <code>.dll</code> file in Windows, a <code>.so</code> file in Linux).
After that, you can load your library directly from within Lua,
with <code>loadlib</code>.
The call
<pre>
    mylib = loadlib("fullname-of-your-library", "luaopen_mylib")
</pre>
transforms the <code>luaopen_mylib</code> function into a C function
inside Lua and assigns this function to <code>mylib</code>.
(That explains why <code>luaopen_mylib</code> must have the same
prototype as any other C function.)
Next, the call <code>mylib()</code> runs <code>luaopen_mylib</code>, opening the library.

<p>If your interpreter does not support dynamic linking,
then you have to recompile Lua with your new library.
Besides that, you need some way to tell the stand-alone interpreter
that it should open this library when it opens a new state.
Some macros facilitate this task.
First, you must create a header file
(let us call it <code>mylib.h</code>) with the following content:
<pre>
    int luaopen_mylib (lua_State *L);
    
    #define LUA_EXTRALIBS { "mylib", luaopen_mylib },
</pre>
The first line declares the open function.
The next line defines the macro <code>LUA_EXTRALIBS</code>
as a new entry in the array of functions that the
interpreter calls when it creates a new state.
(This array has type <code>struct luaL_reg[]</code>,
so we need to put a name there.)

<p>To include this header file in the interpreter,
you can define the macro <code>LUA_USERCONFIG</code> in your compiler options.
For a command-line compiler,
you typically must add an option like
<pre>
    -DLUA_USERCONFIG=\"mylib.h\"
</pre>
(The backslashes protect the quotes from the shell;
those quotes are necessary in C
when we specify an include file name.)
In an integrated development environment,
you must add something similar in the project settings.
Then, when you re-compile <code>lua.c</code>,
it includes <code>mylib.h</code>, and therefore uses
the new definition of <code>LUA_EXTRALIBS</code> in
the list of libraries to open.

<p>
<hr/>
<table width="100%" class="nav">
<tr valign="top">
<td width="90%" align="left">
<small>
  Copyright &copy; 2003&ndash;2004 Roberto Ierusalimschy.  All rights reserved.
</small>
</td>
<td width="10%" align="right"><a href="27.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
</table>


</body></html>

